package TestDemo;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {

    }
    TreeNode(int val) {
        this.val = val;
    }
}

public class Main {

    public static int postIdx = 0;
    public static int searchIdx(int[] inorder, int left, int right, int val) {
        for (int i = left; i <= right; i++) {
            if (inorder[i] == val) {
                return i;
            }
        }
        return -1;
    }

    public static TreeNode createTree(int[] inorder, int[] postorder, int left, int right) {
        if (left > right) return null;
        TreeNode root = new TreeNode(postorder[postIdx]);
        int inIdx = searchIdx(inorder, left, right, root.val);
        postIdx--;

        root.right = createTree(inorder, postorder, inIdx + 1, right);
        root.left = createTree(inorder, postorder, left, inIdx - 1);

        return root;
    }

    public static TreeNode buildTree(int[] inorder, int[] postorder) {
        postIdx = postorder.length - 1;
        return createTree(inorder, postorder, 0, postIdx);
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] inorder = new int[n]; // 中序遍历
        int[] postorder = new int[n]; // 后序遍历

        for (int i = 0; i < n; i++) {
            postorder[i] = sc.nextInt();
        }
        for (int i = 0; i < n; i++) {
            inorder[i] = sc.nextInt();
        }

        TreeNode head = buildTree(inorder, postorder);
        Queue<TreeNode> queue = new LinkedList<>(); // 队列
        ArrayList<Integer> arrayList = new ArrayList<>(); // 顺序表
        queue.offer(head);  // 入队列

        // 层序遍历
        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            if (cur != null) {
                arrayList.add(cur.val); // 入顺序表
                queue.offer(cur.left);  // 入队列
                queue.offer(cur.right); // 入队列
            }
        }

        for (int i = 0; i < arrayList.size(); i++) {
            System.out.println(arrayList.get(i));  // 相当于arrayList[i]
            if (i < arrayList.size() - 1) System.out.println(" ");
            else System.out.println("");
        }

    }
}
